<template>
  <div class="dice-bot">
    <div class="dice-header">
      <h3>
        <el-icon><Dice /></el-icon>
        骰娘助手
      </h3>
      <el-button 
        type="primary" 
        size="small" 
        @click="clearHistory"
        :disabled="diceHistory.length === 0"
      >
        清空历史
      </el-button>
    </div>

    <!-- 骰子输入区域 -->
    <div class="dice-input">
      <el-input
        v-model="diceCommand"
        placeholder="输入骰子指令，如：.r 1d100 或 .check 侦查 70"
        @keyup.enter="rollDice"
        :disabled="isRolling"
      >
        <template #append>
          <el-button 
            type="primary" 
            @click="rollDice"
            :loading="isRolling"
            :disabled="!diceCommand.trim()"
          >
            掷骰
          </el-button>
        </template>
      </el-input>
    </div>

    <!-- 快速指令按钮 -->
    <div class="quick-commands">
      <el-button 
        v-for="cmd in quickCommands" 
        :key="cmd.command"
        size="small"
        @click="setCommand(cmd.command)"
      >
        {{ cmd.label }}
      </el-button>
    </div>

    <!-- 3D骰子动画区域 -->
    <div class="dice-animation" v-if="showAnimation">
      <div class="dice-container" ref="diceContainer">
        <div 
          v-for="(dice, index) in animationDice" 
          :key="index"
          class="dice-3d"
          :style="dice.style"
        >
          {{ dice.value }}
        </div>
      </div>
    </div>

    <!-- 骰子历史记录 -->
    <div class="dice-history">
      <h4>掷骰历史</h4>
      <div class="history-list">
        <div 
          v-for="(record, index) in diceHistory" 
          :key="index"
          class="history-item"
          :class="{ 'is-success': record.isSuccess, 'is-failure': record.isSuccess === false }"
        >
          <div class="history-time">{{ formatTime(record.timestamp) }}</div>
          <div class="history-command">{{ record.command }}</div>
          <div class="history-result">{{ record.formattedResult }}</div>
          <div class="history-details" v-if="record.details">
            <div v-for="(detail, i) in record.details" :key="i" class="detail-item">
              {{ detail }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useGameStore } from '@/stores/game'
import DiceParser from '@/utils/diceParser'
import { ElMessage } from 'element-plus'

const gameStore = useGameStore()
const diceParser = new DiceParser()

// 响应式数据
const diceCommand = ref('')
const isRolling = ref(false)
const showAnimation = ref(false)
const animationDice = ref([])
const diceContainer = ref(null)

// 快速指令
const quickCommands = [
  { label: '1d100', command: '.r 1d100' },
  { label: '2d6', command: '.r 2d6' },
  { label: '1d20', command: '.r 1d20' },
  { label: '侦查检定', command: '.check 侦查 70' },
  { label: '聆听检定', command: '.check 聆听 60' },
  { label: '潜行检定', command: '.check 潜行 50' }
]

// 计算属性
const diceHistory = computed(() => gameStore.diceHistory)

// 方法
const setCommand = (command) => {
  diceCommand.value = command
}

const rollDice = async () => {
  if (!diceCommand.value.trim() || isRolling.value) return

  try {
    isRolling.value = true
    showAnimation.value = true

    // 解析骰子指令
    const result = diceParser.parseCommand(diceCommand.value)
    
    // 生成动画骰子
    generateAnimationDice(result)
    
    // 等待动画完成
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 创建记录
    const record = {
      command: result.command,
      result: result,
      formattedResult: diceParser.formatResult(result),
      timestamp: new Date(),
      isSuccess: result.isSuccess,
      details: generateResultDetails(result)
    }

    // 添加到历史记录
    gameStore.addDiceRecord(record)
    
    // 清空输入
    diceCommand.value = ''
    
    // 隐藏动画
    showAnimation.value = false
    
    ElMessage.success('掷骰完成')
    
  } catch (error) {
    ElMessage.error(error.message)
    showAnimation.value = false
  } finally {
    isRolling.value = false
  }
}

const generateAnimationDice = (result) => {
  animationDice.value = []
  
  if (result.type === 'dice') {
    for (const diceResult of result.diceResults) {
      if (diceResult.type === 'dice') {
        for (let i = 0; i < diceResult.count; i++) {
          animationDice.value.push({
            value: diceResult.rolls[i],
            style: {
              left: Math.random() * 200 + 'px',
              top: Math.random() * 100 + 'px',
              animationDelay: Math.random() * 0.5 + 's'
            }
          })
        }
      }
    }
  } else if (result.type === 'check') {
    animationDice.value.push({
      value: result.diceResult,
      style: {
        left: '50%',
        top: '50%',
        transform: 'translate(-50%, -50%)'
      }
    })
  }
}

const generateResultDetails = (result) => {
  const details = []
  
  if (result.type === 'dice') {
    for (const diceResult of result.diceResults) {
      if (diceResult.type === 'dice') {
        details.push(`${diceResult.display}: ${diceResult.rolls.join(', ')}`)
      } else {
        details.push(diceResult.display)
      }
    }
  } else if (result.type === 'check') {
    details.push(`技能值: ${result.skillValue}`)
    details.push(`成功等级: ${result.successLevel}`)
  }
  
  return details
}

const formatTime = (timestamp) => {
  return timestamp.toLocaleTimeString('zh-CN', { 
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const clearHistory = () => {
  gameStore.diceHistory = []
  ElMessage.success('历史记录已清空')
}

// 生命周期
onMounted(() => {
  // 组件挂载时的初始化
})

onUnmounted(() => {
  // 组件卸载时的清理
})
</script>

<style scoped>
.dice-bot {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.dice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.dice-header h3 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #333;
}

.dice-input {
  margin-bottom: 15px;
}

.quick-commands {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.dice-animation {
  position: relative;
  height: 150px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  margin-bottom: 20px;
  overflow: hidden;
}

.dice-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.dice-3d {
  position: absolute;
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 16px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  animation: diceRoll 2s ease-out forwards;
}

@keyframes diceRoll {
  0% {
    transform: translateY(-100px) rotateX(0deg) rotateY(0deg);
    opacity: 0;
  }
  50% {
    transform: translateY(0) rotateX(180deg) rotateY(180deg);
    opacity: 1;
  }
  100% {
    transform: translateY(0) rotateX(360deg) rotateY(360deg);
    opacity: 1;
  }
}

.dice-history {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.dice-history h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  max-height: 300px;
}

.history-item {
  padding: 12px;
  margin-bottom: 8px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #ddd;
  transition: all 0.3s ease;
}

.history-item.is-success {
  border-left-color: #67c23a;
  background: #f0f9ff;
}

.history-item.is-failure {
  border-left-color: #f56c6c;
  background: #fef0f0;
}

.history-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.history-command {
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.history-result {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.history-details {
  font-size: 12px;
  color: #888;
}

.detail-item {
  margin-bottom: 2px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dice-bot {
    padding: 15px;
  }
  
  .quick-commands {
    gap: 6px;
  }
  
  .quick-commands .el-button {
    font-size: 12px;
    padding: 4px 8px;
  }
  
  .dice-animation {
    height: 120px;
  }
  
  .dice-3d {
    width: 30px;
    height: 30px;
    font-size: 14px;
  }
}
</style>
